<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item>
        <el-select
          v-model="type"
          @change="pageGetLinkageExecute"
        >
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="linkageId"
          @change="pageGetLinkageExecute"
        >
          <el-option
            v-for="item in linkageList"
            :key="item.linkageId"
            :label="item.name"
            :value="item.linkageId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="pageGetLinkageExecute">{{ $t('search') }}</el-button>
      </el-form-item>
    </el-form>
    <div
      class="uni-scroll"
      style="height: calc(100vh - 220px)"
    >
      <el-table
        ref="multipleTable"
        :data="linkageExecuteList"
        style="width: 100%;"
      >
        <el-table-column :label="$t('name')">
          <template slot-scope="scope">
            <i :class="scope.row.type==='server' ? 'el-icon-cloudy' : 'el-icon-cpu'" />
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :formatter="formatType"
          :label="$t('type')"
          width="100"
        />
        <el-table-column
          prop="status"
          :label="$t('status')"
          :formatter="formatStatus"
          width="80"
        />
        <el-table-column width="480" :label="$t('trigger')">
          <template slot-scope="scope">
            <div style="display: flex;justify-content: space-between">
              <div v-if="scope.row.type === 's'">
                <div>
                  <el-cascader
                    v-model="scope.row.selectedExplain"
                    disabled
                    style="width: 250px;margin-right: 5px"
                    filterable
                    :options="sensorWithExplainList"
                    expand-trigger="hover"
                  >
                    <template slot-scope="{ node, data }">
                      <span>{{ data.label }}</span>
                      <span style="float: right"> ({{ data.value }}) </span>
                    </template>
                  </el-cascader>

                  <el-select
                    v-model="scope.row.logic"
                    clearable
                    filterable
                    disabled
                    style="width: 80px;margin-right: 5px"
                  >
                    <el-option :label="$t('greater')" value=">" />
                    <el-option :label="$t('less')" value="<" />
                    <el-option :label="$t('equal')" value="=" />
                  </el-select>
                  <el-input v-model="scope.row.value" style="width: 80px" :placeholder="$t('value')" disabled />
                </div>
              </div>
              <div v-else-if="scope.row.type === 't'">
                <el-time-picker
                  v-model="scope.row.timer"
                  disabled
                  value-format="HH:mm"
                  format="HH:mm"
                />
              </div>
              <div v-else-if="scope.row.type === 'i'">
                <el-time-picker
                  v-model="scope.row.timer"
                  disabled
                  value-format="HH:mm"
                  format="HH:mm"
                />
              </div>
              <div v-else-if="scope.row.type === 't2'">
                <el-time-picker
                  v-model="scope.row.startDate"
                  style=";margin-right: 5px"
                  disabled
                  value-format="HH:mm"
                  format="HH:mm"
                  :placeholder="$t('startDate')"
                />
                <el-time-picker
                  v-model="scope.row.endDate"
                  disabled
                  value-format="HH:mm"
                  format="HH:mm"
                  :placeholder="$t('endDate')"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="triggerValue" :label="$t('value')" width="80" />
        <el-table-column :label="$t('time')" width="150">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.createdDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('function')" width="180" >
          <template slot-scope="scope">
            <el-button icon="el-icon-magic-stick" type="text" @click="listLinkageExecuteCondition(scope.row)">{{ $t('condition') }}</el-button>
            <el-button icon="el-icon-s-tools" type="text" @click="listLinkageExecuteSetting(scope.row)">{{ $t('command') }}</el-button>
            <el-button icon="el-icon-delete" type="text" style="color: #FF805F" @click="deleteExecute(scope.row)">{{ $t('delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="text-align: right;margin: 15px 0">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :title="$t('condition')"
      :visible.sync="executeConditionDialogVisible"
    >
      <el-table
        :show-header="false"
        :data="conditionList"
        style="min-height: 200px"
      >
        <el-table-column>
          <template slot-scope="scope">
            <div style="display: flex;justify-content: space-between;align-items: center">
              <div v-if="scope.row.type === 's'">
                <div>
                  <el-cascader
                    v-model="scope.row.selectedExplain"
                    style="width: 250px"
                    :options="sensorWithExplainList"
                    expand-trigger="hover"
                  >
                    <template slot-scope="{ node, data }">
                      <span>{{ data.label }}</span>
                      <span style="float: right"> ({{ data.value }}) </span>
                    </template>
                  </el-cascader>
                  <el-select v-model="scope.row.logic" clearable filterable>
                    <el-option :label="$t('greater')" value=">" />
                    <el-option :label="$t('less')" value="<" />
                    <el-option :label="$t('equal')" value="=" />
                  </el-select>
                  <el-input v-model="scope.row.value" style="width: 150px" />
                </div>
              </div>
              <div v-else-if="scope.row.type === 't2'">
                <div style="margin-bottom: 10px">
                  <el-checkbox
                    disabled
                    :value="scope.row.allDay"
                    style="margin-right: 10px"
                  >{{ $t('allDay') }}</el-checkbox>
                  <el-time-picker
                    v-if="!scope.row.allDay"
                    disabled
                    :value="scope.row.startDate"
                    value-format="HH:mm"
                    format="HH:mm"
                    :placeholder="$t('startDate')"
                  />
                  <el-time-picker
                    v-if="!scope.row.allDay"
                    disabled
                    :value="scope.row.endDate"
                    value-format="HH:mm"
                    format="HH:mm"
                    :placeholder="$t('endDate')"
                  />
                </div>
                <el-checkbox
                  disabled
                  :value="checkDayAll"
                  style="margin-bottom: 10px"
                  :indeterminate="isIndeterminate"
                >{{ $t('week') }}
                </el-checkbox>
                <el-checkbox-group :value="checkDay">
                  <el-checkbox
                    v-for="day in days"
                    :key="day.value"
                    disabled
                    :label="day.value"
                  >{{ day.label }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <el-button
                type="danger"
                class="el-icon-delete"
                @click="delCondition(scope.row)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog
      :title="$t('setting')"
      :visible.sync="executeSettingDialogVisible"
    >
      <el-table
        :show-header="false"
        :data="settingList"
      >
        <el-table-column>
          <template slot-scope="scope">
            <div style="display: flex;justify-content: space-between">
              <el-cascader
                v-model="scope.row.selectedSetting"
                disabled
                style="width: 250px"
                filterable
                :options="sensorWithSettingList"
                expand-trigger="hover"
              />
              <div v-if="scope.row.type === 'fixedParam'">
                <div v-if="scope.row.paramList.length > 5">
                  <el-select
                    v-model="scope.row.value"
                    disabled
                  >
                    <el-option
                      v-for="item in scope.row.paramList"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </div>
                <el-button
                  v-for="(item,index) in scope.row.paramList"
                  v-else
                  :key="index"
                  type="primary"
                  :plain="item.value !== scope.row.value"
                  disabled
                  @click="btnGroupSetting(item)"
                >{{ item.name }}
                </el-button>
              </div>
              <div v-else-if="scope.row.type === 'custom'">
                <el-input
                  v-model="scope.row.value"
                  style="width:300px"
                  disabled
                />
              </div>
              <div v-else-if="scope.row.type === 'switch'">
                <el-switch
                  v-model="scope.row.value"
                  disabled
                  :active-text="$t('open')"
                  :inactive-text="$t('close')"
                  active-value="1"
                  inactive-value="0"
                />
              </div>
              <div v-else-if="scope.row.type === 'time'">
                <el-time-picker
                  v-model="scope.row.value"
                  disabled
                  style="width:300px"
                  value-format="HH:mm"
                  format="HH:mm"
                  :placeholder="$t('timing')"
                />
              </div>
              <div v-else-if="scope.row.type === 'slider'">
                <el-slider
                  v-model="scope.row.value"
                  style="width:360px"
                  disabled
                />
              </div>
              <el-input
                v-if="scope.row.errorCode"
                v-model="scope.row.errorCode"
                disabled
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  formatDate,
  cancelNotice,
  successNotice
} from '@/util/common'
import {
  pageGetLinkageExecute,
  deleteLinkageExecute
} from '@/api/iot/iotDeviceLinkageExcuteApi'
import { listLinkageExecuteSetting } from '@/api/iot/iotDeviceLinkageExcuteSettingApi'
import { listLinkageExecuteCondition } from '@/api/iot/iotDeviceLinkageExcuteConditionApi'
import { listSensorWith } from '@/api/iot/iotDeviceSensorApi'
import { getPageSize, setPageSize } from '@/util/storage'
import {
  listLinkage
} from '@/api/iot/iotDeviceLinkageApi'
export default {
  name: 'LinkageExecute',
  data() {
    return {
      executeSettingDialogVisible: false,
      executeConditionDialogVisible: false,
      linkageExecuteList: [],
      sensorWithExplainList: [],
      sensorWithSettingList: [],
      settingList: [],
      conditionList: [],
      linkageId: null,
      type: null,
      linkageList: [],
      currentPage: 1,
      total: 0,
      pageSize: getPageSize(),
      deviceCore: null,
      deviceName: null,
      mList: [],
      mCheck: false,
      typeList: [],
      isIndeterminate: false,
      checkDayAll: false,
      checkDay: [],
      days: []
    }
  },
  mounted() {
    this.typeList = [
      {
        label: this.$t('all'),
        value: null
      },
      {
        label: this.$t('sensor') + this.$t('trigger'),
        value: 's'
      },
      {
        label: this.$t('timing') + this.$t('trigger'),
        value: 't'
      },
      {
        label: this.$t('interval') + this.$t('trigger'),
        value: 'i'
      },
      {
        label: this.$t('timeSlot') + this.$t('trigger'),
        value: 't2'
      }
    ]
    this.days = [
      {
        label: this.$t('sunday'),
        value: 7
      },
      {
        label: this.$t('monday'),
        value: 1
      },
      {
        label: this.$t('tuesday'),
        value: 2
      },
      {
        label: this.$t('wednesday'),
        value: 3
      },
      {
        label: this.$t('thursday'),
        value: 4
      },
      {
        label: this.$t('friday'),
        value: 5
      },
      {
        label: this.$t('saturday'),
        value: 6
      }
    ]
    const param = this.$route.query
    this.deviceCore = param.deviceCore
    if (param.linkageId) {
      this.linkageId = parseInt(param.linkageId)
    }

    this.deviceName = param.deviceName
    this.listLinkage()
    this.listSensorWithExplain()
    this.listSensorWithSetting()
    this.setTagsViewTitle()
  },
  methods: {
    formatStatus(item) {
      return this.$t(item.status)
    },
    formatType(item) {
      for (const type of this.typeList) {
        if (type.value == item.type) {
          return type.label
        }
      }
    },
    listSensorWithSetting() {
      listSensorWith({
        deviceCore: this.deviceCore,
        withSetting: true,
        canDeviceLinkage: true
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.deviceSettingList = data
          const sensorWithSettingList = []
          for (let i = 0; i < data.length; i++) {
            const sensor = data[i]
            const item = {
              value: sensor.port,
              label: sensor.sensorName,
              children: []
            }
            const settingList = sensor['settingList']
            const settingListLen = settingList.length
            for (let j = 0; j < settingListLen; j++) {
              const setting = settingList[j]
              // if (setting.type === 'fixedParam' || setting.type === 'custom' || setting.type === 'switch' || setting.type === 'time' || setting.type === 'slider') {
              item.children.push({
                value: setting.keyName,
                label: setting.name
              })
              // }
            }
            sensorWithSettingList.push(item)
          }
          this.sensorWithSettingList = sensorWithSettingList
          this.listSensorWithExplain()
        }
      })
    },
    listLinkageExecuteSetting(item) {
      listLinkageExecuteSetting({
        executeId: item.executeId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          const settingList = []
          data.forEach(setting => {
            for (const j in this.deviceSettingList) {
              const sensor = this.deviceSettingList[j]
              for (const k in sensor.settingList) {
                const deviceSetting = sensor.settingList[k]
                if (deviceSetting.keyName === setting.keyName && deviceSetting.port === setting.port) {
                  setting.selectedSetting = [
                    setting.port,
                    setting.keyName
                  ]
                  if (deviceSetting.type === 'slider') {
                    setting.value = parseInt(setting.value)
                  }
                  setting.paramList = deviceSetting.paramList
                  setting.deviceCore = deviceSetting.deviceCore
                  setting.type = deviceSetting.type
                  setting.port = deviceSetting.port
                  setting.name = deviceSetting.name
                  settingList.push(setting)
                  break
                }
              }
            }
          })
          this.settingList = settingList
          this.executeSettingDialogVisible = true
        }
      })
    },
    listLinkageExecuteCondition(item) {
      listLinkageExecuteCondition({
        executeId: item.executeId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          let conditionList = data
          if (conditionList == null || conditionList.length === 0) {
            conditionList = []
          } else {
            for (const index in conditionList) {
              if (conditionList[index].type === 's') {
                conditionList[index].selectedExplain = [
                  conditionList[index].port,
                  conditionList[index].keyName
                ]
              } else if (conditionList[index].type === 't2') {
                if (conditionList[index].allDay === 0) {
                  conditionList[index].allDay = false
                  conditionList[index].startDate = conditionList[
                    index
                  ].timer.split(' / ')[0]
                  conditionList[index].endDate = conditionList[
                    index
                  ].timer.split(' / ')[1]
                } else {
                  conditionList[index].allDay = true
                }
                const day = conditionList[index].day.split('')
                const dayList = []
                for (const i of day) {
                  dayList.push(parseInt(i))
                }
                if (day.length > 0) {
                  if (data.length === 7) {
                    this.isIndeterminate = false
                    this.checkDayAll = true
                  } else {
                    this.isIndeterminate = true
                  }
                } else {
                  this.isIndeterminate = false
                }
                this.checkDay = dayList
              }
            }
          }
          this.conditionList = conditionList
          this.executeConditionDialogVisible = true
        }
      })
    },
    listLinkage() {
      listLinkage({
        deviceCore: this.deviceCore
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          data.unshift({
            linkageId: null,
            name: this.$t('all')
          })
          this.linkageList = data
        } else {
          this.linkageList = []
        }
      })
    },
    listSensorWithExplain() {
      listSensorWith({
        deviceCore: this.deviceCore,
        withExplain: true
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          const sensorWithExplainList = []
          for (let i = 0; i < data.length; i++) {
            const sensor = data[i]
            const item = {
              value: sensor.port,
              label: sensor.sensorName,
              children: []
            }
            const sensorExplainListLen =
                sensor['explainList'].length
            for (let j = 0; j < sensorExplainListLen; j++) {
              const explain = sensor['explainList'][j]
              item.children.push({
                value: explain.keyName,
                label: explain.name
              })
            }
            sensorWithExplainList.push(item)
          }
          this.sensorWithExplainList = sensorWithExplainList
        } else {
          this.sensorWithExplainList = []
        }
        this.pageGetLinkageExecute()
      })
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    deleteExecute(item) {
      const that = this
      this.$confirm(this.$t('delete'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteLinkageExecute({
            executeId: item.executeId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
            }
            that.pageGetLinkageExecute()
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    handleSizeChange(val) {
      this.pageSize = val
      setPageSize(this.pageSize)
      this.pageGetLinkageExecute()
    },
    handleCurrentChange(item) {
      this.currentPage = item
      this.pageGetLinkageExecute()
    },
    pageGetLinkageExecute() {
      pageGetLinkageExecute({
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        linkageId: this.linkageId,
        type: this.type,
        deviceCore: this.deviceCore
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.total = data.total
          let linkageExecuteList = data.data
          if (linkageExecuteList == null) {
            linkageExecuteList = []
          } else {
            for (const index in linkageExecuteList) {
              if (linkageExecuteList[index].type === 's') {
                linkageExecuteList[index].selectedExplain = [
                  linkageExecuteList[index].port,
                  linkageExecuteList[index].keyName
                ]
              } else if (linkageExecuteList[index].type === 't2') {
                linkageExecuteList[index].startDate = linkageExecuteList[index].timer.split(
                  ' / '
                )[0]
                linkageExecuteList[index].endDate = linkageExecuteList[index].timer.split(
                  ' / '
                )[1]
              }
            }
          }
          this.linkageExecuteList = linkageExecuteList
        }
      })
    }
  }
}
</script>
